from trans import *
from ezhangbendef import *
from datetime import datetime, timedelta
import logging

class Statistics(TransRequestHandler):
    """ This is statistics of where the money spends, you can input a
    range to static, it will return the total money spends, in Month
    total statistic, statistic of whom, statisitc on catelog"""

    def apply_year_st(self, qbase, year_str, month_str, the_range_str):
        statisics = 0.0
        try:
            year = int(year_str)
            month = int(month_str)
            the_range = int(the_range_str)
        except ValueError, error:
            return -1

        if month > 12 or year > 9998:
            return -1
        
        if year > 0 or month > 0:
            datebeginstr = str("%d-%d-%d" % (year, month, 1))
            begin_date = datetime.strptime(datebeginstr, "%Y-%m-%d")
            qbase.filter('date >=', begin_date)

            if the_range > 0:
                year  += (the_range / 12)
                month += the_range % 12
                if month >= 12:
                    year += 1
                    month -= 12
                if month == 0:
                    month = 1
                dateendstr = str('%d-%d-%d' % (year, month, 30))
                # logging.debug("end date:%s" % dateendstr)
                end_date = datetime.strptime(dateendstr, "%Y-%m-%d")
                qbase.filter('date <=', end_date)

        for p in qbase:
            statisics += float(p.amountnum)
        return statisics

    def base_st(self):
        qbase = Transcation.all()
        qbase.filter('owner =', users.get_current_user())
        qbase.filter('is_pay = ', True)
        return qbase
    
    def get_catelog_st(self, catelog, year_str, month_str, the_range_str):
        qbase = self.base_st()
        qbase.filter('expense_catelog =', catelog)
        number = self.apply_year_st(qbase, year_str, month_str, the_range_str)
        logging.debug("catelog:%s is %d" % (catelog, number))
        return number
        
    def get_who_st(self, who, year_str, month_str, the_range_str):
        """
        if year == -1, month == -1, statistic all the record.
        if range == -1, statistic from year-month-1  to present.

        return -1 when error
        """
        qbase = self.base_st()
        qbase.filter('expense_to_whom = ', who)
        number = self.apply_year_st(qbase, year_str, month_str, the_range_str)
        logging.debug("whom:%s is %d" % (who, number))
        return number
    
    def get(self):
        """ input should:
        year: start year,
        month: start month,
        range: how long, if this range is < 0, which statistic it to present.

        output:
        <htm>
        <who> <me> NUMBER </me> <lover> NUMBER </lover> <friends> NUMBER </frientds> </who>
        <a id='who'> NUMBER_OF_ME | NUMBER_OF_LOVER | NUMBER_OF_OTHER </a>
        <a id='catelog'> NUMBER_OF_EATING | NUMBER_OF_HOUSING | NUMBER_OF_TRAFFIC | NUMBER_OF_TRAFFIC | NUMBER_OF_ENTERTAIN | NUMBER_OF_SHOOPING | NUMBER_OF_PHONE | NUMBER_OF_BOOK | NUMBER_OF_TRAVEL </a>
        </html>
        """
        year = month = the_range = ""
        onMe = onLover = onFirends = 0
        onEating = onHousing = onTraffic = onTravel = 0
        onEntertain = onShopping = onPhone = onBook = 0
        year = cgi.escape(self.request.get('year'))
        month = cgi.escape(self.request.get('month'))
        the_range = cgi.escape(self.request.get('range')); # Range unit is month
        
        if year == '':
            year = "-1"
        if month == '':
            month = "-1"
        if the_range == '':
            the_range = "-1"

        onFriends       = self.get_who_st('Friends', year, month, the_range)
        onMe            = self.get_who_st('I', year, month, the_range)
        onLover         = self.get_who_st('My Love', year, month, the_range)
        onEating        = self.get_catelog_st('Eating', year, month, the_range)
        onHousing       = self.get_catelog_st('Housing', year, month, the_range)
        onTraffic       = self.get_catelog_st('Traffic', year, month, the_range)
        onEntertain     = self.get_catelog_st('Entertain', year, month, the_range)
        onShopping      = self.get_catelog_st('Shopping', year, month, the_range)
        onPhone         = self.get_catelog_st('Phone', year, month, the_range)
        onBook          = self.get_catelog_st('Book', year, month, the_range)
        onTravel        = self.get_catelog_st('Travel', year, month, the_range)

        # reply it.

        
